﻿#include "dockwidgetctd_imcharts.h"
#include "ui_dockwidgetctd_imcharts.h"
#include <QLegendMarker>
#include <QHeaderView>
#include <QDateTime>
#include <QTimer>
#include <QPen>
#include <QVBoxLayout>
#include <QDebug>
#include "CTDWidget/dockwidgetctd.h"
#include "Template/singleton.h"

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif


DockWidgetCTD_IMCharts::DockWidgetCTD_IMCharts(QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::DockWidgetCTD_IMCharts)
    , timerHeartCTD_IMCharts(new QTimer(this))
    , dockWidgetCTD_IM(DockWidgetCTDInstance)
{
    connect(timerHeartCTD_IMCharts, &QTimer::timeout, this, [=]() {

        dockWidgetCTD_IM->serialPortCTD.write("TSS\r\n");

        });

    ui->setupUi(this);
    setBottomCharts();

    // CTD_IM的信号和槽--> 将tab 和 charts链接
    // 打点的信号和槽
    connect(dockWidgetCTD_IM, &DockWidgetCTD::sendOnceSample, this, &DockWidgetCTD_IMCharts::setOnceSampleCTDIMDataChart);
    // dockWidgetCTD传过来的flag 改变打点状态
    connect(dockWidgetCTD_IM, &DockWidgetCTD::sendChangeStatus, this, &DockWidgetCTD_IMCharts::recvChangeStatus);
    // 本类的打点信号传给 dockWidgetCTD 改变状态
    connect(this, &DockWidgetCTD_IMCharts::sendChangeStatus,dockWidgetCTD_IM, &DockWidgetCTD::recvChangeStatus);

}

DockWidgetCTD_IMCharts::~DockWidgetCTD_IMCharts()
{
    delete ui;
}

void DockWidgetCTD_IMCharts::setBottomCharts()
{
    setFeatures(QDockWidget::DockWidgetMovable);
    setAllowedAreas(Qt::BottomDockWidgetArea);
    setWindowTitle(tr("CTD_IM"));
    QPen dpen;
    dpen.setWidth(2);
    dpen.setColor(QColor(252, 167, 54));
    mChartCTDIM = new QChart;

    m_scatterSeriesCTDIMTemperature = new QScatterSeries();
    m_scatterSeriesCTDIMTemperature->setMarkerSize(8);
    m_scatterSeriesCTDIMTemperature->setColor(QColor(252, 167, 54));
    m_scatterSeriesCTDIMTemperature->setPointsVisible(true);

    m_dseriesTemperature = new QLineSeries;
    m_dseriesTemperature->setPen(dpen);
    //  m_dseries_Temperature->setColor(QColor(252, 167, 54));
    m_dseriesTemperature->setName("温度");  // 设置图例名字


    dpen.setColor(QColor(0, 122, 204));
    m_dseriesConductdivity = new QLineSeries;
    m_dseriesConductdivity->setPen(dpen);
    m_dseriesConductdivity->setName("电导率");  // 设置图例名字

    m_scatterSeriesCTDIMConductdivity = new QScatterSeries();
    m_scatterSeriesCTDIMConductdivity->setMarkerSize(8);
    m_scatterSeriesCTDIMConductdivity->setColor(QColor(0, 122, 204));
    m_scatterSeriesCTDIMConductdivity->setPointsVisible(true);

    dpen.setColor(QColor(47, 172, 49));
    m_dseriesPressure = new QLineSeries;
    m_dseriesPressure->setPen(dpen);
    m_dseriesPressure->setName("压力");  // 设置图例名字

    m_scatterSeriesCTDIMPressure = new QScatterSeries();
    m_scatterSeriesCTDIMPressure->setMarkerSize(8);
    m_scatterSeriesCTDIMPressure->setColor(QColor(47, 172, 49));
    m_scatterSeriesCTDIMPressure->setPointsVisible(true);

    //  m_chart->setTitle("坐标图");
    mChartCTDIM->addSeries(m_dseriesTemperature);
    mChartCTDIM->addSeries(m_dseriesConductdivity);
    mChartCTDIM->addSeries(m_dseriesPressure);
    mChartCTDIM->addSeries(m_scatterSeriesCTDIMTemperature);
    mChartCTDIM->addSeries(m_scatterSeriesCTDIMConductdivity);
    mChartCTDIM->addSeries(m_scatterSeriesCTDIMPressure);

    QFont font_cutline;
    font_cutline.setFamily("微软雅黑");
    font_cutline.setPointSize(8);
    font_cutline.setBold(true);

    mChartCTDIM->legend()->markers().at(3)->setVisible(false);
    mChartCTDIM->legend()->markers().at(4)->setVisible(false);
    mChartCTDIM->legend()->markers().at(5)->setVisible(false);
    mChartCTDIM->legend()->setFont(QFont("Microsoft YaHei", 10, 70));

    // 设置X 轴坐标
    m_Time_daxisX = new QDateTimeAxis();
    m_Time_daxisX->colorChanged(QColor(32, 159, 223));
    m_Time_daxisX->setTitleText("Time");
    m_Time_daxisX->setTickCount(5);                // 设置X轴坐标网格数
    m_Time_daxisX->setFormat("h:mm:ss");
    m_Time_daxisX->setLabelsFont(QFont("Microsoft YaHei", 10, 70));

    QDateTime xMin, xMax;  // 设置时间坐标轴范围
    xMin = QDateTime::currentDateTime();
    xMax = xMin.addSecs(20);
    m_Time_daxisX->setRange(xMin, xMax);

    // 设置 Y 轴坐标
    daxisY_Temperature = new QValueAxis(this);
    QFont font_y_Temperature;
    font_y_Temperature.setFamily(QString("Microsoft YaHei"));
    font_y_Temperature.setPointSize(8);
    font_y_Temperature.setBold(true);
    daxisY_Temperature->setLabelsFont(font_y_Temperature);
    daxisY_Temperature->setTitleText("Temperature(°C)");
    daxisY_Temperature->setTitleBrush(QColor(252, 167, 54));
    daxisY_Temperature->setRange(0, 10);
    daxisY_Temperature->setTickCount(5); // 设置Y轴坐标网格数
    daxisY_Temperature->setLabelFormat("%.4f");
    daxisY_Temperature->setLinePenColor(QColor(252, 167, 54));
    daxisY_Temperature->setLabelsColor(QColor(252, 167, 54));

    daxisY_Conductivity = new QValueAxis(this);
    daxisY_Conductivity->setLabelsFont(font_y_Temperature);
    daxisY_Conductivity->setTitleText("Conductivity(mS/cm)");
    daxisY_Conductivity->setTitleBrush(QColor(0, 122, 204));
    daxisY_Conductivity->setRange(0, 10);
    daxisY_Conductivity->setTickCount(5); // 设置Y轴坐标网格数
    daxisY_Conductivity->setLabelFormat("%.4f");
    daxisY_Conductivity->setLinePenColor(QColor(0, 122, 204));
    daxisY_Conductivity->setLabelsColor(QColor(0, 122, 204));
    
    daxisY_Pressure = new QValueAxis(this);
    daxisY_Pressure->setLabelsFont(font_y_Temperature);
    daxisY_Pressure->setTitleText("Pressure(dbar)");
    daxisY_Pressure->setTitleBrush(QColor(47, 172, 49));
    daxisY_Pressure->setRange(0, 10);
    daxisY_Pressure->setTickCount(5); // 设置Y轴坐标网格数
    daxisY_Pressure->setLabelFormat("%.4f");
    daxisY_Pressure->setLinePenColor(QColor(47, 172, 49));
    daxisY_Pressure->setLabelsColor(QColor(47, 172, 49));

    mChartCTDIM->addAxis(m_Time_daxisX, Qt::AlignBottom);
    mChartCTDIM->addAxis(daxisY_Pressure, Qt::AlignLeft);
    mChartCTDIM->addAxis(daxisY_Temperature, Qt::AlignLeft);
    mChartCTDIM->addAxis(daxisY_Conductivity, Qt::AlignLeft);


    // 温度线和温度点附加上去
    m_dseriesTemperature->attachAxis(m_Time_daxisX);
    m_dseriesTemperature->attachAxis(daxisY_Temperature);

    m_scatterSeriesCTDIMTemperature->attachAxis(m_Time_daxisX);
    m_scatterSeriesCTDIMTemperature->attachAxis(daxisY_Temperature);

    m_dseriesConductdivity->attachAxis(m_Time_daxisX);
    m_dseriesConductdivity->attachAxis(daxisY_Conductivity);

    m_scatterSeriesCTDIMConductdivity->attachAxis(m_Time_daxisX);
    m_scatterSeriesCTDIMConductdivity->attachAxis(daxisY_Conductivity);

    m_dseriesPressure->attachAxis(m_Time_daxisX);
    m_dseriesPressure->attachAxis(daxisY_Pressure);

    m_scatterSeriesCTDIMPressure->attachAxis(m_Time_daxisX);
    m_scatterSeriesCTDIMPressure->attachAxis(daxisY_Pressure);


    dchartView = new QChartView(mChartCTDIM, this);
    dchartView->setRenderHint(QPainter::Antialiasing);

    mBottomTableWidget = new QTableWidget();
    // 设置列数
    mBottomTableWidget->setColumnCount(3);
    // 设置行数
    mBottomTableWidget->setRowCount(3);
    // 设置垂直表头不可见
    mBottomTableWidget->verticalHeader()->setVisible(false);
    // 表头标题用QStringList来表示
    QStringList headerTest;
    //headerTest<<QStringLiteral("数值")<<QStringLiteral("最新取样值")<<QStringLiteral("单位");
    headerTest << "功能" << "最新取样值" << "单位";
    mBottomTableWidget->setHorizontalHeaderLabels(headerTest);
    mBottomTableWidget->horizontalHeader()->setFont(QFont("Microsoft YaHei", 10, 70));
    mBottomTableWidget->setEditTriggers(QTableWidget::NoEditTriggers);
    // 设置整行选中模式
    mBottomTableWidget->setSelectionBehavior(QTableWidget::SelectRows);
    // 设置单选模式
    mBottomTableWidget->setSelectionMode(QTableWidget::SingleSelection);
    // 设置最后一行自适应长度
    mBottomTableWidget->horizontalHeader()->setStretchLastSection(true);

    QTableWidgetItem* unitConductivityItem = new QTableWidgetItem("电导率");
    unitConductivityItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    unitConductivityItem->setForeground(QColor(0, 122, 204));
    unitConductivityItem->setFont(QFont("Microsoft YaHei", 10, 70));
    mBottomTableWidget->setItem(0, 0, unitConductivityItem);

    QTableWidgetItem* itemConductivity = new QTableWidgetItem("mS/cm");
    itemConductivity->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    itemConductivity->setForeground(QColor(0, 122, 204));
    itemConductivity->setFont(QFont("Microsoft YaHei", 10, 70));
    mBottomTableWidget->setItem(0, 2, itemConductivity);

    QTableWidgetItem* itemTemperature = new QTableWidgetItem("温度");
    itemTemperature->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    itemTemperature->setForeground(QColor(252, 167, 54));
    itemTemperature->setFont(QFont("Microsoft YaHei", 10, 70));
    mBottomTableWidget->setItem(1, 0, itemTemperature);

    QTableWidgetItem* unitTemperature = new QTableWidgetItem("°C");
    unitTemperature->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    unitTemperature->setForeground(QColor(252, 167, 54));
    unitTemperature->setFont(QFont("Microsoft YaHei", 10, 70));
    mBottomTableWidget->setItem(1, 2, unitTemperature);

    QTableWidgetItem* itemPressure = new QTableWidgetItem("压力");
    itemPressure->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    itemPressure->setForeground(QColor(47, 172, 49));
    itemPressure->setFont(QFont("Microsoft YaHei", 10, 70));
    mBottomTableWidget->setItem(2, 0, itemPressure);

    QTableWidgetItem* unitPressure = new QTableWidgetItem("dbar");
    unitPressure->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    unitPressure->setForeground(QColor(47, 172, 49));
    unitPressure->setFont(QFont("Microsoft YaHei", 10, 70));
    mBottomTableWidget->setItem(2, 2, unitPressure);

    mLabelSampleCount = new QLabel();
    mLabelSampleCount->setFont(QFont("Microsoft YaHei", 10, 70));
    mLabelSampleCount->setText(QString("Sample #:%1(captured)").arg(mSanpleCount));

    mSampleTime = new QLabel();
    mSampleTime->setFont(QFont("Microsoft YaHei", 10, 70));
    mSampleTime->setText(QString("Time: %1").arg(" "));


    // 开启轮训
    mButtonRotate = new QPushButton(this);
    mButtonRotate->setFont(QFont("Microsoft YaHei", 10, 70));
    mButtonRotate->setText(tr("开启轮询"));
    mButtonRotate->setFixedSize(80, 30);


    // 垂直布局 上下结构
    mVLayout = new QVBoxLayout();
    mVLayout->addWidget(mButtonRotate);
    //m_vLayout->addWidget(m_Label_Sample_Save_Location);
    mVLayout->addWidget(mLabelSampleCount);
    mVLayout->addWidget(mSampleTime);
    mVLayout->addWidget(mBottomTableWidget);
    mVLayout->setDirection(QBoxLayout::TopToBottom);

    mRightBottom = new QWidget();
    mRightBottom->setLayout(mVLayout);

    mHLayout = new QHBoxLayout();
    // m_hLayout->addWidget(dchartView);
    mHLayout->addWidget(dchartView);
    mHLayout->addWidget(mRightBottom);
    mHLayout->setDirection(QBoxLayout::LeftToRight);
    // 比例
    mHLayout->setStretchFactor(dchartView, 5);
    mHLayout->setStretchFactor(mRightBottom, 1);
    //ui->dockWidget_3->setWidget(dchartView);
    //ui->dockWidgetContents->setLayout(m_hLayout);
    QWidget* widget = new QWidget(this);
    widget->setLayout(mHLayout);
    //this->layout()->addWidget(widget);
    //ui->dockWidgetContents->layout()->addWidget(widget);

    setWidget(widget);

    // 开启循环
    connect(mButtonRotate, &QPushButton::clicked, this, [=]() {
        if (startSampleFlag)
        {
            startSampleFlag = false;
            timerHeartCTD_IMCharts->start(1000);
            mButtonRotate->setText(tr("关闭轮询"));

            emit sendChangeStatus(false);
            
        }
        else
        {
            startSampleFlag = true;
            timerHeartCTD_IMCharts->stop();
            mButtonRotate->setText(tr("开启轮询"));

            emit sendChangeStatus(true);
        }

        });
}

void DockWidgetCTD_IMCharts::recvChangeStatus(bool flag)
{
    // 单独改变下面打点按钮的状态
    mButtonRotate->setEnabled(flag);
}


void DockWidgetCTD_IMCharts::setOnceSampleCTDIMDataChart(QByteArray& data)
{
    // "$PRMSE,000.0002,030.9506,-0000.06,23-08-21,11:12:07\r\n>"
    
    auto&& arrData =  data.split(',');
    double arrConductdivity = arrData.at(1).toDouble();
    double arrTemperature = arrData.at(2).toDouble();
    double arrPressure = arrData.at(3).toDouble();
    QByteArray arrDateTimeFront = arrData.at(4);
    QByteArray arrDateTimeBack =  arrData.at(5);
    arrDateTimeBack.replace('\r', "").replace('\n', "").replace('>', "");
    arrDateTimeFront.append(" "+ arrDateTimeBack);
    
    if (mFirstSampleCTD_IM)
    {
        mFirstSampleCTD_IM = false;
        mMaxC = arrConductdivity;
        mMaxT = arrTemperature;
        mMaxD = arrPressure;
    }
    // 最大和最小电导率
    mMaxC = mMaxC < arrConductdivity ? arrConductdivity : mMaxC;
    mMinC = mMinC > arrConductdivity ? arrConductdivity : mMinC;
    // 最大和最小温度
    mMaxT = mMaxT < arrConductdivity ? arrConductdivity : mMaxT;
    mMinT = mMinT > arrConductdivity ? arrConductdivity : mMinT;
    // 最大和最小压力
    mMaxD = mMaxD < arrConductdivity ? arrConductdivity : mMaxD;
    mMinD = mMinD > arrConductdivity ? arrConductdivity : mMinD;

    // 设置电导率量程
    daxisY_Conductivity->setRange(mMinC,mMaxC+0.001);
    // 温度量程
    daxisY_Temperature->setRange(mMinT,mMaxT+1);
    // 压力量程
    daxisY_Temperature->setRange(mMinD,mMaxD+0.01);

    QString currDatetime = QString("20" + arrDateTimeFront);
    if (m_currDatetime == currDatetime)
    {
        qDebug() << "Once Sample time is error";
        return;
    }

    // 初始化采样次数和时间
    mLabelSampleCount->setFont(QFont("Microsoft YaHei", 10, 70));
    mLabelSampleCount->setText(QString("Sample #:%1(captured)").arg(++mSanpleCount));
    mSampleTime->setFont(QFont("Microsoft YaHei", 10, 70));
    mSampleTime->setText(QString("Time: %1").arg(currDatetime));
    QDateTime currTime = QDateTime::fromString(currDatetime, "yyyy-MM-dd hh:mm:ss");

    if (mFirstSimple)
    {
        // 再次更新坐标轴
        QDateTime xMin, xMax;  // 设置时间坐标轴范围
        xMin = currTime.toLocalTime();
        xMax = xMin.addSecs(20);
        m_Time_daxisX->setRange(xMin, xMax);
        mFirstSimple = false;
    }

    QFont font_cutline;
    font_cutline.setFamily("微软雅黑");
    font_cutline.setPointSize(8);
    font_cutline.setBold(true);

    QDateTime t(currTime);
    m_dseriesTemperature->append(t.toMSecsSinceEpoch(), arrTemperature);
    m_scatterSeriesCTDIMTemperature->append(t.toMSecsSinceEpoch(), arrTemperature);

    m_dseriesConductdivity->append(t.toMSecsSinceEpoch(), arrConductdivity);
    m_scatterSeriesCTDIMConductdivity->append(t.toMSecsSinceEpoch(), arrConductdivity);

    m_dseriesPressure->append(t.toMSecsSinceEpoch(), arrPressure);
    m_scatterSeriesCTDIMPressure->append(t.toMSecsSinceEpoch(), arrPressure);
    
    // m_dseries_Pressure->append(t.toMSecsSinceEpoch(), sourcePressure);
    // m_scatterSeries_P->append(t.toMSecsSinceEpoch(), sourcePressure);


     // 设置表
     m_New_Value_Conductdivity = new QTableWidgetItem(QString::number(arrConductdivity, 'f', 4));
     m_New_Value_Conductdivity->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
     m_New_Value_Conductdivity->setTextColor(QColor(0,122,204));
     m_New_Value_Conductdivity->setFont(QFont("Microsoft YaHei", 10, 70));

     m_New_Value_Temperature = new QTableWidgetItem(QString::number(arrTemperature, 'f', 4));
     m_New_Value_Temperature->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
     m_New_Value_Temperature->setTextColor(QColor(252,167,54));
     m_New_Value_Temperature->setFont(QFont("Microsoft YaHei", 10, 70));

     m_New_Value_Pressure = new QTableWidgetItem(QString::number(arrPressure, 'f', 4));
     m_New_Value_Pressure->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
     m_New_Value_Pressure->setTextColor(QColor(47,172,49));
     m_New_Value_Pressure->setFont(QFont("Microsoft YaHei", 10, 70));


     mBottomTableWidget->setItem(0, 1, m_New_Value_Conductdivity);
     mBottomTableWidget->setItem(1, 1, m_New_Value_Temperature);
     mBottomTableWidget->setItem(2, 1, m_New_Value_Pressure);

     if (currTime > m_Time_daxisX->max())
     {
         QDateTime xMin;
         xMin = currTime.addSecs(qint64(-20));
         m_Time_daxisX->setRange(xMin, currTime);
     }
     m_currDatetime = currDatetime;

}